package client.comm.commlib.base

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import client.comm.commlib.dialog.UpdateVersionDialog
import client.comm.commlib.toast.ToastFactory
import client.comm.commlib.toast.ToastFactory.Companion.isSnackBack
import client.comm.commlib.utils.Util
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager

open abstract class BaseActivity<VM : ViewModel, V : ViewDataBinding> :
    AppCompatActivity() {
    lateinit var binding: V
    lateinit var viewModel: VM

    val C_TAG = "baoding"

    val mImgLoader: RequestManager by lazy {
        getImgLoader()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (getLayout() > 0) {
            setTheme()
            binding = DataBindingUtil.setContentView(this, getLayout())
            binding.lifecycleOwner = this

            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        viewModel = initViewModel()

        initBundle(savedInstanceState)
        initView()
        initData()
        observerUI()

        lifecycleScope.launchWhenCreated { }
    }

    open abstract fun getLayout(): Int
    abstract fun initViewModel(): VM
    open fun initView() {}
    open fun initData() {}
    open fun setTheme() {}
    open fun initBundle(savedInstanceState: Bundle?) {}

    protected open fun observerUI() {}

    inline fun <reified VM : ViewModel> createViewModel(): VM {
        return viewModels<VM> { ViewModelProvider.AndroidViewModelFactory(application) }.value
    }

    var changeSize: Float = 1f //设置默认字号

    override fun onConfigurationChanged(newConfig: Configuration) {
        if (newConfig.fontScale !== changeSize) //非默认值
            resources
        super.onConfigurationChanged(newConfig)
    }

    override fun getResources(): Resources? {
        val res = super.getResources()
        if (res.configuration.fontScale != changeSize) { //非默认值
            val newConfig = Configuration()
            newConfig.setToDefaults() //设置默认
            newConfig.fontScale = changeSize
            res.updateConfiguration(newConfig, res.displayMetrics)
        }
        return res
    }

    /**
     * 隐藏软键盘。
     */
    fun hideSoftKeyboard() {
        try {
            val view = currentFocus
            if (view != null) {
                val binder = view.windowToken
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(binder, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        } catch (e: Exception) {
        }

    }

    /**
     * 显示软键盘。
     */
    fun showSoftKeyboard(editText: EditText?) {
        try {
            if (editText != null) {
                editText.requestFocus()
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.showSoftInput(editText, 0)
            }
        } catch (e: Exception) {
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("DD", "onActivityResult $requestCode")
        when (requestCode) {
            UpdateVersionDialog.GET_UNKNOWN_APP_SOURCES -> {
                Util.checkOreoAndInstallApk()
            }

        }
    }

    override fun onResume() {
        super.onResume()
        if (!isSnackBack) {
            custumResume()
            parentOnresuse?.invoke()
        } else
            isSnackBack = false
    }

    var parentOnresuse: (() -> Unit)? = null

    open fun custumResume() {}

    open fun dipToPx(resources: Resources, dp: Float): Float {
        val metrics = resources.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics)
    }

    @Synchronized
    open fun getImgLoader(): RequestManager {
        return Glide.with(this)
    }
}